package com.nantai.jiafang.nantaijiafang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.MyApplication;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.adapter.FebricBatchListAdapter;
import com.nantai.jiafang.nantaijiafang.bean.FabricBatchInfo;
import com.nantai.jiafang.nantaijiafang.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
//面料批次利用率信息数据展示界面
public class FabricBatchUsageActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_back;
    private TextView tv_title;
    private Button btn_read;
    private Button btn_unread;
    private ListView lv_read;
    private List<FabricBatchInfo> list_read;
    private Context mContext;
    private String timeStamp = "";
    private DbManager db;
    private FebricBatchListAdapter adapter1;
    private FebricBatchListAdapter adapter2;
    private Button btn_setallread;
    private Spinner spinner_select;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_message);
        mContext = FabricBatchUsageActivity.this;
        db = x.getDb(MyApplication.daoConfig);
        initViews();
        setup();
    }

    private void initViews() {
        timeStamp = Tools.getSharedValue(mContext, IConstant.FILE_USER, IConstant.SP_TIMESTAMP_FEBRICBATCH);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back = (TextView) findViewById(R.id.tv_back);
        btn_read = (Button) findViewById(R.id.btn_read);
        btn_unread = (Button) findViewById(R.id.btn_unread);
        lv_read = (ListView) findViewById(R.id.lv_read);
        btn_unread.setTextColor(Color.RED);
        btn_setallread = (Button) findViewById(R.id.btn_setallread);
        spinner_select = (Spinner)findViewById(R.id.spinner_select);
    }

    private void setup() {
        btn_setallread.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        btn_unread.setOnClickListener(this);
        btn_read.setOnClickListener(this);
        tv_title.setText("面料批次利用率信息");
        spinner_select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        adapter2.showall();
                        break;
                    default:
                        adapter2.showselect(spinner_select.getSelectedItem().toString());
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        initListViews();

    }

    //更新数据库
    private void updateDB(FabricBatchInfo FabricBatchInfo) {
        try {
            FabricBatchInfo.setIsRead("1");
            db.update(FabricBatchInfo);
        } catch (DbException e) {

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99) {
            getDataFromDB();
        }
    }

    private void initListViews() {
        list_read = new ArrayList<>();
        getDataFromDB();
    }
    //数据库获取数据
    private void getDataFromDB() {
        List<FabricBatchInfo> list = new ArrayList<>();
        list_read.clear();
      /*  try {
            list_read = db.selector(FabricBatchInfo.class).where("Timestamp","=",getIntent().getStringExtra(IConstant.INTENT)).findAll();
        } catch (DbException e) {
            System.out.println("查询数据库出错");
        }*/
        list_read= Data.mianliao_data.get(getIntent().getIntExtra("select",0));
        if (adapter2 == null) {
            adapter2 = new FebricBatchListAdapter(FabricBatchUsageActivity.this, list_read);
            lv_read.setAdapter(adapter2);
        } else {
            adapter2.notifyDataSetChanged();
        }
    }
    //网络获取数据
    private void getDataFromNet() {
        RequestParams params = new RequestParams(IConstant.URL_PUSH);
        params.addBodyParameter("type", "ML");
        params.addBodyParameter("timestamp", timeStamp);

        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("返回结果：" + result);
                Gson gson = new Gson();
                try {
                    JSONObject jo = new JSONObject(result);
                    String str = jo.get("Table").toString();
                    List<FabricBatchInfo> list = gson.fromJson(str, new TypeToken<List<FabricBatchInfo>>() {
                    }.getType());
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setIsRead("0");
                    }
                    insertIntoDB(list);
                    System.out.println("数据大小：" + list.size());
                    //清空此次时间戳和记录条数
                    Tools.setSharedValue(mContext, IConstant.FILE_USER, IConstant.SP_TIMESTAMP_FEBRICBATCH, "");
                    Tools.setSharedValue(mContext, IConstant.FILE_USER, IConstant.SP_COUNT_FEBRICBATCH, "");
                } catch (JSONException e) {
                    System.out.println("GSON出错");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Tools.showToast(mContext, "请求出错，请重试");
                getDataFromDB();
                //System.out.println("出错：" + ex.getCause().toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
                getDataFromDB();
            }

            @Override
            public void onFinished() {
                getDataFromDB();
            }
        });
    }

    //网络获取的数据插入数据库
    private void insertIntoDB(List<FabricBatchInfo> list) {

        try {
            db.save(list);
            getDataFromDB();
        } catch (DbException e) {
            System.out.println("插入数据库出错");
            getDataFromDB();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;

            case R.id.btn_unread:
                lv_read.setVisibility(View.GONE);
                btn_read.setTextColor(Color.BLACK);
                btn_unread.setTextColor(Color.RED);
                break;
            case R.id.btn_read:
                lv_read.setVisibility(View.VISIBLE);
                btn_read.setTextColor(Color.BLUE);
                btn_unread.setTextColor(Color.BLACK);
                break;

            case R.id.btn_setallread:
                try {
                    db.update(FabricBatchInfo.class,
                            WhereBuilder.b("isRead", "=", "0"),
                            new KeyValue("isRead", "1"));
                    getDataFromDB();
                } catch (DbException db) {

                }

                break;

        }
    }

}
